package com.mocoop.dao;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;

import com.mocoop.entity.AjaxInfo;
import com.mocoop.entity.AjaxInfo.UploadAttachmentFilesInfo;

public class AjaxWorkerDaoImp implements AjaxWorkerDao {
	private Context context;
	private String dbName;

	public AjaxWorkerDaoImp(Context context, String dbName) {
		super();
		this.context = context;
		this.dbName = dbName;
	}

	@Override
	public long save(AjaxInfo ajaxInfo) {
		SQLiteDatabase database = SQLiteHelper.getDataBase(context, dbName);
		ContentValues cv = new ContentValues();
		cv.put("FCloudDataTransferURL", ajaxInfo.getUrl());
		cv.put("FCloudDataTransferHTTPMethod", ajaxInfo.getMethod());
		cv.put("FCloudDataTransferRequestData", ajaxInfo.getRequestData());
		cv.put("FCloudDataTransferUploadAttachmentFilesInfo", ajaxInfo.getUploadAttachmentFilesInfo().toString());
		cv.put("FCloudDataTransferCreatedTimeStamp", ajaxInfo.getBeginTime());
		cv.put("FCloudDataTransferExtra", ajaxInfo.getExtra());
		cv.put("FCloudDataTransferSQLOperation", ajaxInfo.getSqlOperation().toString());
		cv.put("FCloudDataTransferNoticePages", ajaxInfo.getNoticePages().toString());
		cv.put("FCloudDataTransferMatchIDs", ajaxInfo.getMatchIDs().toString());
		if (ajaxInfo.getTransferState() != null)
			cv.put("FCloudDataTransferState", ajaxInfo.getTransferState());
		if (ajaxInfo.getErrorMessage() != null)
			cv.put("FCloudDataTransferErrorMessage", ajaxInfo.getErrorMessage());
		long i = database.insert("T_CloudDataTransferCenter", null, cv);
		return i;
	}

	@Override
	public void update(AjaxInfo ajaxInfo) {
		SQLiteDatabase database = SQLiteHelper.getDataBase(context, dbName);
		ContentValues cv = new ContentValues();
		cv.put("FCloudDataTransferEndTimeStamp", ajaxInfo.getEndTime());
		cv.put("FCloudDataTransferState", ajaxInfo.getTransferState());
		cv.put("FCloudDataTransferResponseData", ajaxInfo.getResponseData());
		cv.put("FCloudDataTransferErrorMessage", ajaxInfo.getErrorMessage());
		database.update("T_CloudDataTransferCenter", cv, "FCloudDataTransferID = ?", new String[] { ajaxInfo.getId() + "" });

	}

	@Override
	public List<AjaxInfo> findUnfinishedAjax() {
		SQLiteDatabase database = SQLiteHelper.getDataBase(context, dbName);
		List<AjaxInfo> list = new ArrayList<AjaxInfo>();
		Cursor cursor = database.rawQuery("select * from T_CloudDataTransferCenter where  FCloudDataTransferState = 'failed';", new String[] {});
		list = jointToAjaxInfoList(cursor);
		cursor.close();
		// database.close();
		return list;
	}

	@Override
	public Exception execute(String sql, String[] selectionArgs) {
		SQLiteDatabase database = null;
		try {
			database = SQLiteHelper.getDataBase(context, dbName);
			database.execSQL(sql, selectionArgs);
		} catch (Exception e) {
			return e;
		} finally {
			// database.close();
		}
		return null;

	}

	

	@Override
	public List<AjaxInfo> findUnfinishedAjaxByIDs(String sql) {
		SQLiteDatabase database = SQLiteHelper.getDataBase(context, dbName);
		List<AjaxInfo> list = new ArrayList<AjaxInfo>();
		Cursor cursor = database.rawQuery("select * from T_CloudDataTransferCenter where FCloudDataTransferID in (" + sql + ");", new String[] {});
		list = jointToAjaxInfoList(cursor);
		cursor.close();
		// database.close();
		return list;
	}

	private List<AjaxInfo> jointToAjaxInfoList(Cursor paramCursor) {
		List<AjaxInfo> list = new ArrayList<AjaxInfo>();
		while (paramCursor.moveToNext()) {

			AjaxInfo localAjaxInfo = new AjaxInfo();
			localAjaxInfo.setId(Integer.valueOf(paramCursor.getInt(paramCursor.getColumnIndex("FCloudDataTransferID"))));
			localAjaxInfo.setUrl(paramCursor.getString(paramCursor.getColumnIndex("FCloudDataTransferURL")));
			localAjaxInfo.setMethod(paramCursor.getString(paramCursor.getColumnIndex("FCloudDataTransferHTTPMethod")));
			localAjaxInfo.setRequestData(paramCursor.getString(paramCursor.getColumnIndex("FCloudDataTransferRequestData")));
			localAjaxInfo.setMatchIDs(paramCursor.getString(paramCursor.getColumnIndex("FCloudDataTransferMatchIDs")));

			AjaxInfo.SQLOperation localSQLOperation = new AjaxInfo.SQLOperation();
			try {
				JSONObject localJSONObject = new JSONObject(paramCursor.getString(paramCursor.getColumnIndex("FCloudDataTransferSQLOperation")));
				localSQLOperation.setSQLOfAjaxCompleted(localJSONObject.getString("SQLOfAjaxCompleted"));
				localSQLOperation.setSQLOfAjaxStarted(localJSONObject.getString("SQLOfAjaxStarted"));
				localSQLOperation.setSQLOfAjaxSuccess(localJSONObject.getString("SQLOfAjaxSuccess"));
				localSQLOperation.setSQLOfAjaxException(localJSONObject.getString("SQLOfAjaxException"));
				localAjaxInfo.setSqlOperation(localSQLOperation);

			} catch (JSONException e) {

			}

			try {
				JSONArray jsonArray = new JSONArray(paramCursor.getString(paramCursor.getColumnIndex("FCloudDataTransferUploadAttachmentFilesInfo")));
				List<UploadAttachmentFilesInfo> filelist = new ArrayList<AjaxInfo.UploadAttachmentFilesInfo>();
				if (jsonArray.length() > 0) {
					for (int i = 0; i < jsonArray.length(); i++) {
						UploadAttachmentFilesInfo attachmentFilesInfo = new UploadAttachmentFilesInfo();
						attachmentFilesInfo.setOriginalFileKey(jsonArray.getJSONObject(i).getString("originalFileKey"));
						attachmentFilesInfo.setOriginalFilePath(jsonArray.getJSONObject(i).getString("originalFilePath"));
						attachmentFilesInfo.setThumbnailFileKey(jsonArray.getJSONObject(i).getString("thumbnailFileKey"));
						attachmentFilesInfo.setThumbnailFilePath(jsonArray.getJSONObject(i).getString("thumbnailFilePath"));
						filelist.add(attachmentFilesInfo);
					}
				}
				localAjaxInfo.setUploadAttachmentFilesInfo(filelist);
			} catch (JSONException e) {

			}

			localAjaxInfo.setNoticePages(paramCursor.getString(paramCursor.getColumnIndex("FCloudDataTransferNoticePages")));
			list.add(localAjaxInfo);
		}
		return list;
	}

	@Override
	public boolean checkFailedExist() {
		SQLiteDatabase database = SQLiteHelper.getDataBase(context, dbName);
		Cursor cursor = database.rawQuery("select * from T_CloudDataTransferCenter where FCloudDataTransferState = 'failed' limit 0,1;",new String[]{});
		boolean isExist = false;
		if(cursor.moveToFirst()){
			isExist = true;
		}
		cursor.close();
		return isExist;
	}

}
